package dao

import (
	"context"
	"go-mall/model"
	"gorm.io/gorm"
)

type OrderDao struct {
	*gorm.DB
}

func NewOrderDao(ctx context.Context) *OrderDao {
	return &OrderDao{NewDBCliet(ctx)}
}

func (dao *OrderDao) CreateOrder(order *model.Order) error {
	return dao.DB.Model(&model.Order{}).Create(order).Error
}

func (dao *OrderDao) CreateOrderItem(orderItem *[]model.OrderItem) error {
	return dao.DB.Model(&model.OrderItem{}).Create(orderItem).Error
}

func (dao *OrderDao) GetOrderById(oId string, uId uint) (order *model.Order, err error) {
	err = dao.DB.Model(&model.Order{}).Where("order_id=? AND user_id = ?", oId, uId).Find(&order).Error
	return
}

func (dao *OrderDao) GetOrderItemById(oId string) (orderItems []*model.OrderItem, err error) {
	err = dao.DB.Model(&model.OrderItem{}).Where("order_id=?", oId).Find(&orderItems).Error
	return
}

func (dao *OrderDao) ListOrder(uId uint, page model.BasePage) (order []*model.Order, total int64, err error) {
	err = dao.DB.Model(&model.Order{}).
		Where("user_id=?", uId).Count(&total).Error
	if err != nil {
		return
	}
	err = dao.DB.Model(&model.Order{}).
		Where("user_id=?", uId).
		Offset((page.PageNum - 1) * (page.PageSize)).Limit(page.PageSize).
		Find(&order).Error
	return
}

func (dao *OrderDao) ListOrderByUserIdAndType(uId uint, site int, page model.BasePage) (order []*model.Order, total int64, err error) {
	err = dao.DB.Model(&model.Order{}).
		Where("user_id=? AND type=?", uId, site).Count(&total).Error
	if err != nil {
		return
	}
	err = dao.DB.Model(&model.Order{}).
		Where("user_id=? AND type=?", uId, site).
		Offset((page.PageNum - 1) * (page.PageSize)).Limit(page.PageSize).
		Find(&order).Error
	return
}

func (dao *OrderDao) DeleteOrderByOrderId(oId, uId uint) error {
	return dao.DB.Model(&model.Order{}).Where("order_id=? AND user_id=?", oId, uId).Delete(&model.Order{}).Error
}
func (dao *OrderDao) DeleteOrderByOrderIdStr(oId string, uId uint) error {
	return dao.DB.Model(&model.Order{}).Where("order_id=? AND user_id=?", oId, uId).Delete(&model.Order{}).Error
}

func (dao *OrderDao) UpdatePayType(oId string) error {
	return dao.DB.Model(&model.Order{}).Where("order_id=?", oId).Update("type", 2).Error
}
